package com.example.controller;

import com.alibaba.druid.sql.dialect.blink.parser.BlinkLexer;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.controller.utils.R;
import com.example.domain.Stu;
import com.example.service.IStuService;
import com.example.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/stus")
public class StuController {

    @Autowired
    private IStuService stuService;

    @GetMapping
    public R getAll(){
        return new R(true,stuService.list());

    }

    @PostMapping
    public R save(@RequestBody Stu stu) throws IOException {
//        R r = new R();
//        boolean flag = stuService.save(stu);
//        r.setFlag(flag);

//        new R(stuService.save(stu));//以上数据可以写成这样，在R中写一个构造函数
        if(stu.getName().equals("1234"))
            throw new IOException();
        boolean flag = stuService.save(stu);
        return new R(flag,flag ? "操作成功^_^" : "操作失败-_-!");
//        return new R(false); //模拟添加失败
    }


    @PutMapping
    public R update(@RequestBody Stu stu){
        return new R(stuService.modify(stu));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(stuService.delete(id));
    }

    @GetMapping("{id}")
    public  R getById(@PathVariable Integer id){
        return new R(true,stuService.getById(id));
    }

//    @GetMapping("{currentPage}/{pageSize}")
//    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize){
//        IPage<Stu> page = stuService.getPage(currentPage, pageSize);
//        if(currentPage > page.getPages()){
//            page = stuService.getPage((int)page.getPages(),pageSize);
//        }
//        return new R(true,page);
//    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize,Stu stu){
        IPage<Stu> page = stuService.getPage(currentPage, pageSize,stu);
        if(currentPage > page.getPages()){
            page = stuService.getPage((int)page.getPages(),pageSize,stu);
        }
        return new R(true,page);
    }
}
